package com.example.userservice.service;

import com.example.userservice.user.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {
    @Insert("INSERT INTO users(username, password, email, phone) " +
            "VALUES(#{username}, #{password}, #{email}, #{phone})")
    @Options(useGeneratedKeys = true, keyProperty = "user_id") // 获取自增ID
    int insert(User user);

    @Select("Select role_id from user_roles where user_id = #{userId}")
    int selectRoleId(Long userId);

    @Select("SELECT user_id from users where username=#{username}")
    Long selectUserId(String username);

    @Select("SELECT u.username " +
            "FROM users u JOIN user_roles ur ON u.user_id = ur.user_id " +
            "WHERE ur.role_id >= (SELECT role_id FROM user_roles WHERE user_id = #{userId})")
    List<String> select(Long userId);

    @Select("SELECT username from users where user_id=#{userId}")
    List<String> selectUsername(Long userId);

    @Select("SELECT u.* " +
            "FROM users u JOIN user_roles ur ON u.user_id = ur.user_id " +
            "WHERE ur.role_id >= (SELECT role_id FROM user_roles WHERE user_id = #{userId})")
    List<User> selectAll(Long userId);

    @Select("SELECT * from users where user_id = #{userId}")
    List<User> selectSelf(Long userId);

    @Update("<script>"+
            "UPDATE users SET email = #{user.email} WHERE user_id = #{user.user_id};" +
            "</script>")
    void changeemail(Long userId,User user);

    @Update("<script>"+
            "UPDATE users SET phone = #{user.phone} WHERE user_id = #{user.user_id};" +
            "</script>")
    void changephone(Long userId,User user);

    @Update("UPDATE users SET password = '1111' WHERE user_id IN " +
            "(SELECT ur.user_id FROM user_roles ur WHERE ur.role_id >= " +
            "(SELECT role_id FROM user_roles WHERE user_id = #{userId}) )")
    void reset(Long userId);

    @Update("UPDATE users SET password = '1111' where user_id = #{userId}")
    void resetPassword(Long userId);
}